<?php

class ProductBaseController extends Controller {

    public $layout = 'main';

    /**
     * @var返回过滤数组
     * @author nirsh
     * @version 5.0
     * @demo 
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * @var返回验证条件 如果不需要验证权限 把$isPriv 设置为allow
     * @author nirsh
     * @version 5.0
     * @demo 
     *    switch($action){
     *      case "login":
     *          $isPriv = 'allow'
     *          break;
     *      default:
     *          $isPriv = $this->checkAccess($controller, $action);
     *      }
     */
    public function accessRules() {
        $controller = Yii::app()->getController()->id;
        $action = Yii::app()->getController()->action->id;
        //登录不需要判断权限
        $isPriv = $this->checkAccess($controller, $action);
        return array(
            array($isPriv,
                'actions' => array($action),
                'users' => array('*'),
            )
        );
    }

    /**
     * 访问某条具体的记录.
     * @param $id 某条记录的主键
     * @author nirsh
     * @demo 
     * @modifly 
     * @version 5.0
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id)
        ));
    }

    /**
     * 创建动作
     * @author nirsh
     * @demo 
     * @modifly 
     * @version 5.0
     */
    public function actionCreate() {
        $model = new ProductBase;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['ProductBase'])) {
            //print_r($_POST);
            //exit;
            $model->attributes = $_POST['ProductBase'];
            if ($model->save()) {
                //保存属性内容
                if (isset($_POST['attr'])) {
                    $attrModel = new ProductAttributeValue;
                    foreach ($_POST['attr'] as $key => $v) {
                        $v = is_array($v) ? serialize($v) : $v;
                        $attrModel->unsetAttributes();
                        $attrModel->setIsNewRecord(true);
                        $attrModel->attributes = array(
                            'product_id' => $model->id,
                            'attribute_id' => $key,
                            'attribute_value' => $v,
                        );
                        if (!$attrModel->insert()) {
                            print_r($attrModel->errors);
                            //exit;
                        }
                    }
                }
                $url = $this->rewriteCreateUrl('view', array('id' => $model->id));
                $this->redirect($url);
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * 更新数据 
     * @param 主键id
     * @author nirsh
     * @demo 
     * @modifly 
     * @version 5.0
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['ProductBase'])) {
            
            $model->attributes = $_POST['ProductBase'];
            if ($model->save()) {
                //保存属性内容
                if (isset($_POST['attr'])) {
                    $attrModel = new ProductAttributeValue;
                    foreach ($_POST['attr'] as $key => $v) {
                        $attrModel->unsetAttributes();
                        $attrModel->setIsNewRecord(true);
                        $v = is_array($v) ? serialize($v) : $v;
                        $data = $attrModel->findByAttributes(array(
                            'product_id' => $model->id,
                            'attribute_id' => $key,
                                ));
                        $attrModel->attributes = array(
                            'product_id' => $model->id,
                            'attribute_id' => $key,
                            'attribute_value' => $v,
                        );
                        if($data)
                        {
                            $data->attributes = $attrModel->attributes;
                            $data->update();
                        }
                        else
                        {
                            $attrModel->insert();
                        }
                                                
                    }
                }
                $url = $this->rewriteCreateUrl('view', array('id' => $model->id));
                $this->redirect($url);
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * 删除记录 
     * @param 主键id
     * @author nirsh
     * @demo 
     * @modifly 
     * @version 5.0
     */
    public function actionDelete() {
        $sId = $_REQUEST['id'];
        $attrVModel = new ProductAttributeValue;
        if(strpos($sId, ',') !== false){
            $sId = explode(',', $sId);
        }
        if (is_array($sId)) {
            foreach ($sId as $id) {
                $tModel = $this->loadModel($id);
                $tModel->delete();
                $attrVModel->deleteAllByAttributes(array('product_id' => $id));
            }
        } else {
            $tModel = $this->loadModel($sId);
            $tModel->delete();
            $attrVModel->deleteAllByAttributes(array('product_id' => $sId));
        }
        if (isset($_REQUEST['ajax'])) {
            echo "数据删除成功";
        } else {
            $this->redirect($_SERVER['HTTP_REFERER']);
        }
    }

    /**
     * 列表动作 
     * @param 主键id
     * @author nirsh
     * @demo 
     * @modifly 
     * @version 5.0
     */
    public function actionIndex() {
        $model = new ProductBase('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_REQUEST['ProductBase']))
            $model->attributes = $_REQUEST['ProductBase'];

        $this->render('index', array(
            'model' => $model,
        ));
    }

    /**
     * 数据管理
     * @param 主键id
     * @author nirsh
     * @demo 
     * @modifly 
     * @version 5.0
     */
    public function actionAdmin() {
        $model = new ProductBase('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_REQUEST['ProductBase']))
            $model->attributes = $_REQUEST['ProductBase'];
        else 
            $model->p_game = 0;

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * 返回数据模型是基于主键所得到的变量 
     * @param 主键id
     * @author nirsh
     * @demo 
     * @modifly 
     * @version 5.0
     */
    public function loadModel($id) {
        $model = ProductBase::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * ajax验证
     * @param 主键id
     * @author nirsh
     * @demo 
     * @modifly 
     * @version 5.0
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'product-base-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /**
     * AJAX操作
     * @author Flowf <freeflowf@gmail.com>
     */
    public function actionAjax() {
        if (Yii::app()->request->isAjaxRequest) {
            switch ($_POST['action']) {
                case 'updateField'://更新字段值
                    $id = (int) $_POST['id'];
                    $field = $_POST['field'];
                    $fieldVal = $_POST['fieldVal'];
                    $model = new ProductBase;
                    echo $model->updateByPk($id, array($field => $fieldVal));
                    break;
                case 'copy'://复制
                    $id = (int) $_POST['id'];
                    $model = ProductBase::model()->findByPk($id);
                    $model->setIsNewRecord(TRUE);
                    $model->id = NULL;
                    echo $model->save();
                    break;
            }
        }
    }

}
